<template>
  <div :style="drawer?'right: 468px;':''" class="shopCar">
    <div class="shopCar-bar" @click="handleShopCarTab">
      <!-- <i class="el-icon-shopping-cart-2"/>
      <div class="name">购<br>物<br>车</div> -->
      <img src="../../../assets/medium/shopCar.png" alt="">
      <div class="name">{{ drawer?'收起':'购物车' }}</div>
      <!-- <div v-if="listLength" class="num">{{ listLength | shopCarNum }}</div> -->
    </div>
    <el-drawer
      :visible="drawer"
      :before-close="handleShopCarTab"
      :modal="false"
      :show-close="false"
      size="458"
      direction="rtl">
      <div
        v-loading="createLoading"
        class="shop-car-body">
        <div class="shop-car-data-order">
          <div class="title-box"><div class="title">询单详情</div></div>
          <div class="shop-car-data-order-form">
            <div class="shop-form-item">
              <span class="name is-required">品牌名称</span>
              <input v-model="params.brandName" class="input" type="text" placeholder="请输入品牌名称">
            </div>
            <div class="shop-form-item">
              <span class="name is-required">需求内容</span>
              <input v-model="params.content" class="input" maxlength="500" type="text" placeholder="请输入需求内容">
            </div>
            <div class="shop-form-item wrap">
              <span class="name is-required">时间</span>
              <el-date-picker
                v-model="params.timeRange"
                :editable="false"
                type="daterange"
                popper-class="shop-popper-date"
                value-format="timestamp"
                size="small"
                format="yyyy/MM/dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>
            </div>
            <div class="shop-form-item response-time">
              <span class="name is-required" >响应时间</span>
              <el-date-picker
                v-model="params.responseTime"
                :picker-options="pickerOptions"
                :editable="false"
                type="datetime"
                size="small"
                popper-class="shopcar-time-select"
                format="yyyy/MM/dd HH:mm:ss"
                value-format="timestamp"
                placeholder="选择日期"/>
            </div>
            <div class="shop-form-item">
              <span class="name">超链接</span>
              <input v-model="params.hyperlinks" class="input" maxlength="500" type="text" placeholder="请输入超链接">
            </div>
            <div class="shop-form-item">
              <span class="name">备注</span>
              <input v-model="params.remarks" class="input" maxlength="500" type="text" placeholder="请输入备注信息">
            </div>
            <div class="shop-form-item">
              <span class="name">附件</span>
              <div class="upload-wrap">
                <Upload
                  ref="shopCarUpload"
                  :import-api="'/admin/medium/file/upload'"
                  :hide-confirm="true"
                  btn-text="上传文件"
                  style="width: 120px;"
                  @upProgress="upProgress"
                  @complateSetData="complateSetData" />
                <span v-if="file && fileName" class="clearFile-icon el-icon-circle-close" @click="clearFile"/>
              </div>
            </div>
            <div v-if="!shopCarList || shopCarList.length <= 0" class="shop-form-item" style="justify-content:center;">
              <div class="btn" style="width: 200px;margin-top:30px;" @click="createOrder(1)">生成泛询单</div>
            </div>
          </div>
        </div>
        <template v-if="shopCarList && shopCarList.length>0" class="shop-car-data-list-continer">
          <div class="shop-data-top">
            <div class="shop-data-title">
              <img class="icon" src="../../../assets/medium/shopCarTitle.png" alt="">
              <span>资源列表</span>
              <div class="sub-title">（共{{ listLength }}个）</div>
            </div>
            <export-button
              ref="exportButton"
              :query-data="exportParams"
              :is-before-export="true"
              :export-api="exportApi"
              :medium-btn-style="mediumBtnStyle"
              btn-text="导出"
              export-name="资源列表"
              @beforeExport="beforeExport"
              @onComplate="completeExport"
            />
            <div class="clear-btn" @click="deleteShopCar('all')">清空 <img src="../../../assets/medium/clear.png" alt=""> </div>
          </div>
          <div id="shop-car-data-list" :style="{height: listHeight}" class="shop-car-data-list">
            <el-scrollbar class="shop-scroll-container">
              <div v-for="(i) in shopCarList" :key="i.platform" class="shop-car-platform">
                <div class="title">
                  {{ i.platform | mediumPlatform }}
                  <span v-if="i.items && i.items.length" class="title-num">（{{ i.items.length }}）</span>
                </div>
                <div class="shop-car-order-list">
                  <div v-for="item in i.items" :key="item.mediumId" class="shop-car-order-item">
                    <div class="avatar">{{ item.avatarName }}</div>
                    <div class="info">
                      <div class="name">{{ item.accountName }}</div>
                      <div class="num">ID：
                        <a
                          v-if="item.accountId.indexOf('http') >= 0"
                          :href="item.accountId"
                          target="_blank"
                          class="link-name">
                          点击跳转<img src="../../../assets/medium/link.png" alt="">
                        </a>
                        <span v-else>{{ item.accountId }}</span>
                      </div>
                      <div v-if="item.organization" class="num">所属机构：{{ item.organization }}</div>
                    </div>
                    <div class="close-item">
                      <i class="el-icon-close" @click="deleteShopCar(item.mediumId, i.platform)" />
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <div class="btn-container" style="display:flex;align-tiems:center;margin-top: 5px;justify-content:center;">
            <div class="btn" style="width: 130px;" @click="createOrder(3)">生成定向询单</div>
            <div class="btn" style="width: 130px;" @click="createOrder(2)">生成全向询单</div>
          </div>
        </template>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import Upload from '@/components/MediumPage/uploadFile';
import ExportButton from '@/components/ExportButton';
import { mediumPlatform } from '@/filters/medium';
import { createOrder } from '@/api/medium';

export default {
  name: 'ShopCar',
  components: { Upload, ExportButton },
  filters: {
    mediumPlatform,
    shopCarNum(num) {
      if (Number(num > 99)) {
        return '99+';
      }
      return num;
    }
  },
  data() {
    return {
      drawer: false,
      createLoading: false,
      platForm: 5,
      orderNum: 4,
      listHeight: 0,
      params: {
        timeRange: [],
        brandName: '',
        responseTime: '',
        remarks: '',
        content: '',
        hyperlinks: ''
      },
      file: '',
      fileName: '',
      exportApi: '/admin/medium/export/order',
      exportParams: {
        ids: ''
      },
      mediumBtnStyle: {
        color: '#fff',
        borderRadius: '4px',
        textAlign: 'center',
        backgroundColor: '#406EFF',
        fontSize: '13px',
        height: '32px',
        marginRight: '10px',
        padding: '0 20px',
        fontWeight: 'bold',
        lineHeight: '32px',
        cursor: 'pointer'
      },
      pickerOptions: {
        disabledDate: (time) => {
          const nowDay = new Date(new Date().setHours(0, 0, 0, 0));
          return time.getTime() < nowDay;
        }
      }
    };
  },
  computed: {
    ...mapState({
      'shopCarList': state => state.medium.shopCarList
    }),
    listLength() {
      const shopCarList = this.shopCarList;
      if (shopCarList.length > 0) {
        let len = 0;
        shopCarList.forEach(i => {
          len = i.items.length + len;
        });
        return len;
      }
      return 0;
    }
  },
  created() {
    this.setListHeight();
  },
  methods: {
    createOrder(type) {
      // type（1、泛询单，2、全向订单、3、定向订单）
      const shopCarList = this.shopCarList;
      const { brandName, timeRange, responseTime, remarks, content, hyperlinks } = this.params;
      if (brandName === '') {
        this.$message({ type: 'warning', message: '请输入品牌名称' });
        return;
      }
      if (content === '') {
        this.$message({ type: 'warning', message: '请输入需求内容' });
        return;
      }
      if (brandName.length > 20) {
        this.$message({ type: 'warning', message: '请输入小于20个字的品牌名称' });
        return;
      }
      if (timeRange.length !== 2) {
        this.$message({ type: 'warning', message: '请选择时间' });
        return;
      }
      if (responseTime === '') {
        this.$message({ type: 'warning', message: '请选择响应时间' });
        return;
      }
      const now = Date.now();
      if (responseTime < now) {
        this.$message({ type: 'warning', message: '响应时间不能早已当前时间' });
        return;
      }
      if (remarks.length > 500) {
        this.$message({ type: 'warning', message: '请输入小于500个字的备注' });
        return;
      }
      const ids = [];
      shopCarList.forEach(i => {
        i.items.forEach(item => {
          ids.push(item.mediumId);
        });
      });
      const params = {
        orderType: type,
        brandName, responseTime,
        startTime: timeRange[0],
        endTime: timeRange[1],
        remarks: remarks || '',
        content: content || '',
        hyperlinks: hyperlinks || ''
      };
      if (params.orderType !== 1) params.ids = ids.join(',');
      if (this.file && this.file !== '') params.file = this.file;
      if (this.fileName && this.fileName !== '') params.fileName = this.fileName;
      this.toCreate(params);
    },
    async toCreate(params) {
      try {
        this.createLoading = true;
        const res = await createOrder(params);
        this.createLoading = false;
        if (res.code === 200) {
          this.$message({ type: 'success', message: '创建成功' });
          this.init();
          this.handleShopCarTab();
          this.confirm(res.data);
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        this.createLoading = false;
        // this.$message({ type: 'error', message: error.message });
      }
    },
    confirm(id) {
      this.$confirm('询单已生成，请在询单中心查看详情信息', '', {
        confirmButtonText: '去看看',
        cancelButtonText: '知道了',
        center: true,
        type: 'warning',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        if (id) {
          this.$router.push({
            name: 'ConsultOrderDetail',
            params: { id }
          });
        } else {
          this.$router.push({
            name: 'ConsultOrder'
          });
        }
      }).catch(() => {
      });
    },
    init() {
      this.params = {
        timeRange: [],
        brandName: '',
        responseTime: '',
        remarks: ''
      };
      this.$store.dispatch('clearShopCar');
    },
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      if (typeof data === 'string') {
        this.file = data;
      } else {
        this.file = data.url;
      }
      this.fileName = fileName;
      // this.$message({ type: 'success', message: '上传成功' });
    },
    // 导出excel前调用的方法
    beforeExport() {
      const shopCarList = this.shopCarList;
      if (shopCarList.length <= 0) return;
      const ids = [];
      shopCarList.forEach(i => {
        i.items.forEach(j => {
          ids.push(j.mediumId);
        });
      });
      this.exportLoading = true;
      this.exportParams.ids = ids.join(',');
      this.$refs.exportButton.btnExport();
    },
    completeExport() {
      this.exportLoading = false;
    },
    handleShopCarTab() {
      this.drawer = !this.drawer;
      this.setListHeight();
    },
    setListHeight() {
      this.$nextTick(() => {
        const listHeight = window.innerHeight - 360 - 120;
        const scrollbar = document.querySelector('.shop-car-data-list .el-scrollbar__view');
        if (scrollbar && scrollbar.offsetHeight < listHeight) {
          this.listHeight = scrollbar.offsetHeight + 5 + 'px';
        } else {
          this.listHeight = listHeight + 'px';
        }
      });
    },
    deleteShopCar(mediumId, platform) {
      if (mediumId !== 'all') {
        this.$store.dispatch('deleteShopCar', { mediumId, platform });
        this.setListHeight();
      } else if (this.shopCarList.length) {
        this.$confirm('是否清空购物车？', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          lockScroll: false,
          customClass: 'del-message del-message-cancel',
          iconClass: 'del-icon'
        }).then(() => {
          this.$store.dispatch('clearShopCar');
        }).catch(() => {});
      }
    },
    clearFile() {
      if (this.$refs.shopCarUpload) this.$refs.shopCarUpload.clearFile();
      this.file = '';
      this.fileName = '';
    }
  }
};
</script>
<style lang="scss" scoped>
.shopCar {
  position: fixed;
  right: 80px;
  bottom: 70px;
  display: flex;
  z-index: 999;
  align-items: center;
  justify-content: center;

  width:105px;
  height:34px;
  background:rgba(255,255,255,1);
  box-shadow:1px 2px 5px 0px rgba(221,225,234,1);
  border-radius:17px;
  .shopCar-bar {
    cursor: pointer;
    display: flex;
    align-items: center;
    .el-icon-shopping-cart-2 {
      font-size: 23px;
      color: #ccc;
      width: 100%;
      text-align: center;
      display: inline-block;
      margin-left: -3px;
    }
    img {
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }
    .name {
      font-size: 14px;
      color: #406EFF;
      font-family:PingFangSC-Medium,PingFang SC;
      font-weight:500;
    }
    .num {
      font-size: 14px;
      text-align: center;
    }
  }
  .shop-car-body {
    height: 100%;
    padding: 20px 22px 0 22px;
    .shop-car-data-list-continer {
      border-top: 1px solid #EBEEFD;
      height: 100%;
    }
    .shop-car-data-list {
      margin-bottom: 10px;
      max-height: calc(100% - 340px - 120px);
      .shop-car-platform {
        margin-bottom: 5px;
        .title-num {
          font-weight: 500;
          font-size: 12px;
        }
        .title {
          color: #333;
          font-size: 14px;
          font-weight: 900;
          position: relative;
          padding-left: 10px;
          margin-bottom: 5px;
          &::before {
            content: '';
            width: 4px;
            height: 12px;
            top: 50%;
            margin-top: -6px;
            position: absolute;
            left: 0;
            background-color: #406EFF;
          }
        }
        .shop-car-order-list {
          padding: 0 12px;
          .shop-car-order-item {
            display: flex;
            align-items: center;
            padding: 20px 0;
            border-bottom: 1px solid #eee;
            .avatar {
              width:36px;
              height:36px;
              background:linear-gradient(167deg,rgba(116,167,255,1) 0%,rgba(64,110,255,1) 100%);
              overflow: hidden;
              border-radius: 100%;
              border: 1px solid #eee;
              font-size: 12px;
              color: #fff;
              text-align: center;
              line-height: 36px;
              img {
                width: 100%;
                height: 100%;
                border-radius: 100%;
                object-fit: cover;
              }
            }
            .info {
              margin-left: 10px;
              width: 300px;
              margin-right: 10px;
              .name {
                margin-bottom: 2px;
                color: #333;
                font-size: 13px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
              .num {
                margin-bottom: 2px;
                color: #999999;
                font-size: 13px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
            &:hover {
              .close-item {display: block;}
            }
            .close-item {
              display: none;
              .el-icon-close {
                font-size: 20px;
                color: #ccc;
                cursor: pointer;
              }
            }
            &:last-child{
              border-bottom: 0;
            }
          }
        }
      }
      .shop-scroll-container {
        width: 100%;
        height: 100%;
        & ::v-deep {
          .el-scrollbar__wrap {
            overflow-x: hidden;
          }
        }
      }
    }
    .shop-car-data-order {
      height: 340px;
      .title-box{
        background-color: #fff;
        padding: 0 10px;
        display: flex;
        align-content: center;
      }
      .title {
        height: 33px;
        line-height: 33px;
        position: relative;
        padding-left: 10px;
        font-size:20px;
        font-family:PingFangSC-Regular,PingFang SC;
        color:rgba(51,51,51,1);
        &::before {
          content: '';
          width: 4px;
          height: 20px;
          top: 50%;
          margin-top: -10px;
          position: absolute;
          left: 0;
          background-color: #406EFF;
        }
      }
      .shop-car-data-order-form {
        .shop-form-item {
          display: flex;
          align-items: center;
          padding: 0 20px;
          padding-right: 20px;
          margin-top: 13px;
          &.wrap {
            & ::v-deep {
              .el-range-editor--small {
                &.el-input__inner {
                  height: 32px;
                  width: 240px;
                }
                .el-range-input {
                  font-size: 12px;
                  text-align: left;
                  text-indent: 8px;
                }
                .el-range__close-icon {
                  width: 14px;
                }
              }
            }
          }
          &.response-time {
            & ::v-deep {
              .el-input--small {
                .el-input__inner {
                  height: 30px;
                  width: 240px;
                }
              }
            }
          }
          .name {
            font-size:14px;
            font-family:PingFangSC-Regular,PingFang SC;
            font-weight:400;
            color:rgba(102,102,102,1);
            line-height:14px;
            width: 80px;
            position: relative;
            margin-right: 20px;
            &.is-required {
              &::before {
                content: '*';
                color: #F56C6C;
                margin-right: 4px;
                position: absolute;
                top: 2px;
                left: -12px;
              }
            }
          }
          .input {
            border-radius: 4px;
            outline: none;
            border: 1px solid #ddd;
            height: 32px;
            padding: 0 10px;
            font-size: 13px;
            width: 240px;
          }
          .file {
            height: 30px;
            line-height: 30px;
          }
        }
      }
    }
  }
  & ::v-deep {
    input::placeholder {
      color: #999999;
    }
    .el-drawer__container {
      cursor: pointer;
      .el-drawer {
        position: absolute;
        cursor: auto;
        width: 458px !important;
        // height: 86%;
        border-radius: 6px;
        box-shadow:
          0 8px 10px -5px rgba(0, 0, 0, 0.2),
          0 16px 24px 2px rgba(0, 0, 0, 0.14),
          0 6px 10px 0px rgba(0, 0, 0, 0.12);
      }
      .el-drawer__header {
        display: none;
      }
      .el-drawer__body {
        height: calc(100% - 60px);
      }
    }
  }
}
.link-name {
  display: inline-block;
  color: #406EFF;
  img {
    position: relative;
    top: 1px;
    width: 11px;
    margin-left: 3px;
  }
  &:hover{
    color: #6e8fa2;
  }
  .el-icon-link {
    font-size: 12px;
  }
}
.gray {
  background-color: #cdcdcd !important;
}
.clearFile-icon  {
  color: #ddd;
  font-size: 16px;
  margin-left: 10px;
  cursor: pointer;
  display: none;
}
.upload-wrap {
  display: flex;
  align-items: center;
  &:hover {
    .clearFile-icon {
      display: block;
    }
  }
}
.shop-data-top {
  display: flex;
  align-items: center;
  padding: 15px 0;
  .shop-data-title {
    display: flex;
    align-items: center;
    font-size:16px;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color:rgba(51,51,51,1);
    line-height:20px;
    flex: 1;
    .icon {
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }
    .sub-title {
      font-size:14px;
      font-family:PingFangSC-Regular,PingFang SC;
      font-weight:400;
      color:rgba(153,153,153,1);
      line-height:14px;
    }
  }
}
.clear-btn {
  display: flex;
  align-items: center;
  font-size:15px;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  line-height:16px;
  margin-left: 24px;
  cursor: pointer;
  position: relative;
  top: 1px;
  img {
    width: 16px;
    height: 16px;
    margin-left: 5px;
  }
}
.btn {
  color: #fff;
  border-radius: 4px;
  text-align: center;
  background-color: #406EFF;
  font-size: 13px;
  height: 32px;
  margin-right: 10px;
  padding: 0 20px;
  font-weight: bold;
  line-height: 32px;
  cursor: pointer;
}
</style>
<style lang="scss">
.shopcar-time-select {
  transform: translateX(-40px);
  z-index: 3000 !important;
}
.shop-popper-date  {
  z-index: 3000 !important;
}
</style>
